import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
  LoginData,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    groupId: undefined,
    groupName: undefined,
    groupType: undefined,
    userId: undefined,
    loginName: undefined,
    mobileNo: undefined,
    userName: undefined,
    role: ''
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles(role:any) {
      return new Promise((resolve) => {
        this.role = role;
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      try {
        // const res = await getUserInfo();
        // localStorage.setItem("role",res.data.result.role);
        // localStorage.setItem("community",""+ res.data.result.community);
        // localStorage.setItem("street",""+ res.data.result.street);
        this.setInfo({role:'admin'});
      } catch (error: any) {
        console.log(error.response.status);
        if(error.response.status === 401){
          this.logoutCallBack();
        }
        throw error;
      }
    },
    sleep(time:number){
      return new Promise((resolve) => setTimeout(resolve, time));
    },

    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        setToken(res.data.result.access_token);
        const date = Date.now();
        let currentDate:any = null;
        do {
           currentDate = Date.now();
        } while (currentDate - date < 300);
        return res;
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      // try {
      //   await userLogout();
      // } finally {
      //   this.logoutCallBack();
      // }
      this.logoutCallBack();
    },
  },
});

export default useUserStore;
